﻿#ifndef IM_DataBuffer_h__
#define IM_DataBuffer_h__

#include <list>
#include <cassert>
#include <cstring>
#include "Utility.h"

#define _DEBUG
#include "Log.h"

struct message
{
	char *buffer;
	int  size;
};

class IM_DataBuffer
{
public:
	void push_data(char * data, int size)
	{
		message m;
		m.buffer = data;
		m.size = size;
		m_mesage_list.push_back(m);
		this->m_size += size;
	}

	void read_data(char *buffer, int size)
	{
		assert(m_size >= size);
		m_size -= size;
		while (true)
		{
			auto current = m_mesage_list.begin();
			int bsz = current->size - m_offset;
			if (bsz>size)
			{
				memcpy(buffer, current->buffer + m_offset, size);
				m_offset += size;
				return;
			}
			if (bsz==size)
			{
				memcpy(buffer, current->buffer + m_offset, size);
				m_offset = 0;
				delete current->buffer;
				m_mesage_list.pop_front();
				return;
			}
			else
			{
				memcpy(buffer, current->buffer + m_offset, bsz);
				m_offset = 0;
				buffer += bsz;
				size -= bsz;
				delete current->buffer;
				m_mesage_list.pop_front();
			}
		}
	}

	//返回 数据包的头部   即 数据的大小  
	//  -1   表示不能读取  
	/*
	@header_size   头部的大小
	*/
	int read_header(int header_size)
	{
		if (this->m_header==0)
		{
			if (m_size<header_size)
			{
				DEBUG("错误！\n");
				return -1;
			}
			uint8_t plen[4];
			read_data((char*)plen, header_size);
			//
			if (header_size==2)
			{
				m_header = Utility::big_to_ilittle_endian_16(plen);
			}
			else
			{
				m_header = Utility::big_to_ilittle_endian_32(plen);
			}

		}
		if (m_size<m_header)
		{
			DEBUG("不能读取\n");
			return -1;    //不能读取  
		}
		
		return m_header;
	}

	//重置buffer
	void reset_databuffer() { m_header = 0; }
private:
	int m_header;
	int m_offset;
	int m_size;
	std::list<message>  m_mesage_list;
};


#endif // IM_DataBuffer_h__
